<?php
/*
 * @Author: your name
 * @Date: 2020-06-06 13:32:49
 * @LastEditTime: 2020-06-06 15:30:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hotel\application\api\controller\Index.php
 */
namespace app\api\controller;

use think\Controller;
use think\Db;

error_reporting(0);
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 允许的响应类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
// 响应头设置
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
class Timer extends Controller
{   
    
    
 
     
    //定时任务--改变用户优惠券表的过期时间
    public function couponUser(){
        
        
        $couponlist = db('coupon_user')
            ->where("end_time!=0  and  status!=2")
            ->select();
        
        foreach($secondlist as $k=>&$v){
            db('coupon_user')->where(['id'=>$v['id'],'endtime'=>['lt',time()]])->update(['status'=>2]);
        }
         
        
        $time = time()-30*60; 
        
        db('order')->where(['status'=>0,'addtime'=>['lt',$time]])->update(['status'=>7]);
        
          
        
    }
    
    //未支付订单发送模板消息
    public function nopay(){
         
        // file_put_contents('send.log', "2222-".time() . "\n", FILE_APPEND);
        //查找订单 
        $end_time = time()-15*60;  
        $end_time = time();
		$orderlist = db('order') 
		    ->alias("a")
		    ->join('think_user b','a.user_id=b.user_id')
		    ->join('think_room c','a.room_id=c.id','left')
		    ->join('think_room_cate d','c.two_cate=d.id','left')
		    ->field('a.order_id,a.user_id,a.money,a.order_number,a.userlist,d.title,b.openid')
		    ->where(['a.status'=>0,'a.addtime'=>['lt',$end_time],'a.is_send'=>0]) 
		    ->select();
// 		return json($orderlist);
		//发送模板消息 
	    $this->nopaysendtemplate($orderlist);
	    
	    
        //发送短信
        return $this->notpaysendMsgs($orderlist);
		
    }
    
    
    //未支付订单发送模板消息
    public function nopaysendtemplate($orderlist){
        
        $first = db('smg_reply')->where(['id'=>2])->value('content');      
		
		$url = request()->server("REQUEST_SCHEME") . "://" . $_SERVER['SERVER_NAME']."/mobile/orderman.html";
		
		foreach($orderlist as $k=>&$v){  
		   
            db('order')->where(['order_id'=>$v['order_id']])->update(['is_send'=>1]);   
             
            
            $hotel = db('hotel')->where(['id'=>1])->value('title');
            
            $template = array(
                'touser' => $v['openid'],
                'template_id' => "MA3tw0I7oxDrPP0VTMECo9GeYjzWErkGrJmwdT_A9T4", //这个是模版ID，获取方法自己看文档很详细。
                'url' => $url,
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => array('value' => $first, 'color' => "#000"),
                    'keyword1' => array('value' => $hotel, 'color' => '#000'),
                    'keyword2' => array('value' => $v['title'], 'color' => '#000'),
                    'keyword3' => array('value' => $v['money'], 'color' => '#000'), 
                    'remark'  => array('value' => "点击查看详情!", 'color' => '#000'),
                )
            );
             
    		$res= (new Sendtemp())->sendMessage($template);
    	    
			//这里就是遍历推送到各个openID了、sleep（1）是为了防止推送过快出问题
			sleep(0.3); 
		 
		}  
    }
    
    
    
    //未支付订单发送短信消息
    public function notpaysendMsgs($orderlist){
		foreach($orderlist as $k=>&$v){
		    db('order')->where(['order_id'=>$v['order_id']])->update(['is_send'=>1]);   
		    $user = db('user')->where(['user_id'=>$v['user_id']])->find();
			//获取手机号码
			 
			if($user['phone']){
			     $content = "您还有一个订单：{$v['order_number']}还未付款，为保证您后续的使用，请进款付款，否则订单将会自动过期！【禅寓酒店】";
		        //发送短信
		        
                $list =  send_msg($user['phone'],$content); 
                return json($list);
			}
           
           
		}  
    }
    
    
    // 改变数据库时间
    public function updatetimer(){
        $mon = date('m')-1;
        $year = date('Y');
        if($mon == 0){
            $mon = 12;
            $year = date('Y')-1;
        }
        
        $date = $year.'-'.$mon.'-';
        $newdate = ($year+4).'-'.$mon.'-'.$day;
        $res = db('time')->where(['date'=>['like',$date.'%']])->select();
        foreach($res as $i=>$item){
            $arr = explode('-',$item['date']);
            $arr[0] = $arr[0]+4;
            $arr = implode('-',$arr);
            db('time')->where(['id'=>$item['id']])->update(['date'=>$arr]);
        }
        return true;
    }
    
    
    //待入住订单发送消息
    public function preparego(){
          
        //查找订单-- 到店时间前一个小时 
        $end_time = time()+60*60;  
        $start_time = time()+56*60; 
		$orderlist = db('order') 
		    ->alias("a") 
		    ->join('think_room c','a.room_id=c.id','left')
		    ->join('think_room_cate d','c.two_cate=d.id','left')
		    ->field('a.order_id,a.order_number,a.go_time,a.userlist,a.room_num,d.title')
		    ->where(['a.status'=>1,'a.go_time'=>['between',[$start_time,$end_time]],'a.is_send'=>0])   
		    ->select();
	 
		//查找酒店地址
		$address = db('hotel')->where(['id'=>1])->value('address');
		
        foreach($orderlist as $k=>&$v){  
		    
		    db('order')->where(['order_id'=>$v['order_id']])->update(['is_send'=>1]);   
			//获取手机号码
            
            $content = "您有{$v['room_num']}间{$v['title']}可以入住了，订单号：{$v['order_number']}，{$address}，距您预约入住时间还有一个小时，请凭有效证件办理入住！";
		    //发送短信
            $list = send_msg($v['phone'],$content); 
		
            return $list;
        } 
         
        
    }
    
    
    
    public function gobirthdy(){
        
        $list = db('user')->where('idcard!=""')->field('user_id,idcard,phone,nickname')->select();
        
           
        $gobirthdy = date('m-d',strtotime('+1week'));
        
        foreach($list as $k=>&$v){
            $birthday = $this->getIDCardInfo($v['idcard']);
            
            if($birthday['error']==2){
                if($gobirthdy==$birthday['birthday']){
                    //查找用户的生日券
                    $find = db('coupon_user')->where(['user_id'=>$v['user_id'],'get_time'=>date('Y-m-d')])->find();
                    if(empty($find)){
                        //发放优惠券
                        $coupon = db('coupon')
                            ->where(['cate_id'=>2,'is_activity'=>0,'status'=>0])
                            ->where("number>0")
                            ->order('start_time desc')
                            ->find();
                        if($coupon['endtime']==0){
                            $endtime = 0;
                        }else{
                            $endtime = time()+$coupon['endtime']*24*3600;
                        }
                        $data = [
                            'user_id' => $v['user_id'],
                            'coupon_id' => $coupon['id'],
                            'coupon_info' => serialize($coupon),
                            'create_time' => time(),
                            'end_time'=>$endtime,
                            'get_time'=>date('Y-m-d')
                            ];
                        db('coupon_user')->insert($data);
                        
                        if($v['phone']!=""){
                            //发送短信消息 
                            $content = "尊敬的会员{$v['nickname']}，您好，过几天就是您的生日了，禅寓酒店提前祝您生日快乐，并给您发放了特殊福利，请移步禅寓酒店公众号领取！";
                		    //发送短信
                            send_msg($v['phone'],$content); 
                        }
                        
            
                    }
                   
                }
                
            }
            
        }
    }
    
    public function getIDCardInfo($IDCard,$format=1){ 
         $result['error']=0;//0：未知错误，1：身份证格式错误，2：无错误 
         $result['flag']='';//0标示成年，1标示未成年 
         $result['tdate']='';//生日，格式如：2012-11-15 
         if(!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/",$IDCard)){ 
          $result['error']=1; 
          return $result; 
         }else{ 
          if(strlen($IDCard)==18)
          { 
           $tyear=intval(substr($IDCard,6,4)); 
           $tmonth=intval(substr($IDCard,10,2)); 
           $tday=intval(substr($IDCard,12,2)); 
          }
          elseif(strlen($IDCard)==15)
          { 
           $tyear=intval("19".substr($IDCard,6,2)); 
           $tmonth=intval(substr($IDCard,8,2)); 
           $tday=intval(substr($IDCard,10,2)); 
          }
            
          if($tyear>date("Y")||$tyear<(date("Y")-100))
          { 
            $flag=0; 
           }
           elseif($tmonth<0||$tmonth>12)
           { 
            $flag=0; 
           }
           elseif($tday<0||$tday>31)
           { 
            $flag=0; 
           }else
           { 
            if($format)
            {
                if($tmonth<10){
                    $tmonth = '0'.$tmonth;
                }
                if($tday<10){
                    $tday = '0'.$tday;
                }
             $tdate=$tmonth."-".$tday; 
            }
            else
            {
             $tdate=$tmonth."-".$tday; 
            }
              
            if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60)
            { 
             $flag=0; 
            }
            else
            { 
             $flag=1; 
            } 
           }  
         } 
        
         $result['error']=2;//0：未知错误，1：身份证格式错误，2：无错误  
         $result['birthday']=$tdate;//生日日期  
         return $result; 
    }
            
     
}
